package org.redis.cluster.redis.processor;

import java.nio.ByteBuffer;

import org.redis.cluster.processor.RedisReplyProcessor;
import org.redis.cluster.redis.transport.RedisReply;
import org.redis.cluster.redis.transport.reply.RedisBulkReply;

public class RedisBulkReplyProcessor implements RedisReplyProcessor<RedisBulkReply> {
	
	private final static int OTHER_BYTE_COUNT=5;
	
	private final static byte[] NULL={RedisReply.LENGTH_START,RedisReply.NULL,RedisReply.END_1,RedisReply.END_2};

	@Override
	public byte[] process(RedisBulkReply reply) {
		Object value=reply.getValue();
		if(value==null) {
			return NULL;
		}
		
		byte bytes[]=(value instanceof byte[]?((byte[])value):value.toString().getBytes());
		byte parameterLengthByte[]=String.valueOf(bytes.length).getBytes();
		ByteBuffer buffer=ByteBuffer.allocate(bytes.length+parameterLengthByte.length+OTHER_BYTE_COUNT);
		
		buffer.put(RedisReply.LENGTH_START);
		buffer.put(parameterLengthByte);
		buffer.put(RedisReply.END_1);
		buffer.put(RedisReply.END_2);
		
		buffer.put(bytes);
		buffer.put(RedisReply.END_1);
		buffer.put(RedisReply.END_2);
		
		return buffer.array();
	}

	@Override
	public Class<? extends RedisReply> getSupportClass() {
		return RedisBulkReply.class;
	}

}